package com.atguigu.demo.servlet;

import com.alibaba.fastjson.JSON;
import com.atguigu.demo.entity.Page;
import com.atguigu.demo.entity.Result;
import com.atguigu.demo.entity.Tiger;
import com.atguigu.demo.service.api.TigerService;
import com.atguigu.demo.service.impl.TigerServiceImpl;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;

@WebServlet(name = "TigerServletPage", value = "/TigerServletPage")
public class TigerServletPage extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        TigerService tigerService = new TigerServiceImpl();

        // 1、从请求参数中获取分页相关数据
        // [1]页码
        String pageNum = request.getParameter("pageNum");

        // [2]页容量
        String pageSize = request.getParameter("pageSize");

        // [3]查询条件
        String tigerNameCondition = request.getParameter("tigerName");

        // ※附加操作：检查 pageNum 和 pageSize 是否有值，并且进行类型转换
        Integer pageNumInt = (pageNum == null) ? Page.DEFAULT_PAGE_NUM : Integer.parseInt(pageNum);
        Integer pageSizeInt = (pageSize == null) ? Page.DEFAULT_PAGE_SIZE : Math.abs(Integer.parseInt(pageSize));

        // 2、调用 Service 方法获取 Page 对象
        Page<Tiger> tigerPage = tigerService.getTigerPage(pageNumInt, pageSizeInt, tigerNameCondition);

        // 3、把 Page 对象封装为 JSON 字符串
        String jsonString = JSON.toJSONString(Result.ok(tigerPage));

        // 4、返回响应
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(jsonString);
    }
}
